﻿using UnityEngine;
using System.Collections;

public class Basics6:MonoBehaviour {
	public NetworkPlayer owner ;
	
	//messages/bandwidth.
	private float lastClientHInput =0;
	private float lastClientVInput  =0;
	
	private float serverCurrentHInput   = 0;
	private float serverCurrentVInput   = 0;
	void Awake(){
		if(Network.isClient){
			enabled=false;
		}
	}

	void Update(){
		if(owner!=null && Network.player==owner){
			float HInput   = Input.GetAxis("Horizontal");
			float VInput   = Input.GetAxis("Vertical");
			if(lastClientHInput!=HInput || lastClientVInput!=VInput ){
				lastClientHInput = HInput;
				lastClientVInput = VInput;
				if(Network.isServer){
					SendMovementInput(HInput, VInput);
				}else if(Network.isClient){
					networkView.RPC("SendMovementInput", RPCMode.Server, HInput, VInput);
				}
			}
		}


		if(Network.isServer){
			Vector3 moveDirection   = new Vector3(serverCurrentHInput, 0,serverCurrentVInput);
			float speed   = 30f;
			transform.Translate(speed * moveDirection * Time.deltaTime);
		}
	}


	[RPC]
	void SetPlayer(NetworkPlayer player ){
		owner = player;
		if(player==Network.player){
			enabled=true;
		}
	}


	[RPC]
	void SendMovementInput(float HInput  ,float VInput  ){
		serverCurrentHInput = HInput;
		serverCurrentVInput = VInput;
	}


	void OnSerializeNetworkView(BitStream stream  , NetworkMessageInfo info  )
	{
		if (stream.isWriting){
			Vector3 pos   = transform.position;
			stream.Serialize(ref pos);
		}else{
			Vector3  posReceive   = Vector3.zero;
			stream.Serialize(ref posReceive); 
			transform.position = posReceive;
		}
	}
}
